package com.mjk.manager.monitor.work;

import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.util.FileUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;

/**
 * 服务版本上传
 */
@RestController
@RequestMapping("/file")
public class ServerVerionUploadController {

    @PostMapping("/upload")
    public BeeResponse versionFileUpload(@RequestParam("file") MultipartFile file, String serverFilePath) {
        if (file.isEmpty()) {
            return BeeError.SYSTEM_UPLOAD_FILE_IS_EMPTY.tranceError();
        }
        try {
            String uploadPath = "";
            if (!serverFilePath.endsWith("\\")) {
                uploadPath = serverFilePath + "\\upload\\";
            } else {
                uploadPath = serverFilePath + "upload\\";
            }
            File f = new File(uploadPath);
            if (!f.exists()) {
                f.mkdirs();
            }
            // 保存文件到服务器的uploadDir目录
            byte[] bytes = file.getBytes();
            java.nio.file.Path path = java.nio.file.Paths.get(uploadPath + file.getOriginalFilename());
            java.nio.file.Files.write(path, bytes);
            //解压文件到备份目录
            File[] files = f.listFiles();
            if (null != files && files.length > 0) {
                for (File tmp : files) {
                    if (!tmp.isDirectory() && tmp.getName().equals(file.getOriginalFilename())) {
                        String fileName = tmp.getName().substring(0, tmp.getName().lastIndexOf(".") + 1);
                        FileUtils.del(serverFilePath + "/backup/" + fileName + "/");
                        String cmd = tmp.getPath().replace(" ", "\" \"") + " " + serverFilePath.replace(" ", "\" \"") + "/backup/" + fileName.replace(" ", "\" \"") + "/";
                        Process process = Runtime.getRuntime().exec("winrar x " + cmd);
                        int exitCode = process.waitFor();
                        Files.delete(path);
                        if (exitCode == 0) {
                            return BeeError.BEE_SUC.tranceError();
                        } else {
                            return BeeError.BEE_FAILD.tranceError();
                        }
                    }
                }
            } else {
                return BeeError.SYSTEM_SERVEIC_VERSION_IS_NULL.tranceError();
            }
            return BeeError.BEE_SUC.tranceError();
        } catch (Exception e) {
            Thread.currentThread().interrupt();
            return BeeError.BEE_FAILD.tranceError();
        }
    }
}
